<template>
  <div class="spurs-dialog">
    <el-dialog
      v-model="dialogVisible"
      :append-to-body="true"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      width="60%"
    >
      <selfProductList @tabledataChoose="tabledataChoose"></selfProductList>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="saveSubmit"> 确 定 </el-button>
          <slot name="footer"></slot>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, reactive, onMounted, computed } from "vue";
// import SpursForm from "@/components/SpursForm/index.vue";
import selfProductList from "@/views/product/info/createOrderIndex.vue";
import { getFormConfig } from "@/components/addEditDialog/selfProduct/FormConfig";
import { ElMessage, FormRules } from "element-plus";
import cloneDeep from "lodash/cloneDeep";
import orderApi from "@/api/order";
import productApi from "@/api/product";
import type { UploadUserFile } from "element-plus";
import { FormOption } from "@/components/SpursForm/formType";
const formConfig = ref<FormOption>({
  formItems: [],
  labelWidth: "120px",
});
const categoryList = ref<{ id: string; name: string }[]>([]);
const spursFormRef = ref<any>();
const rules = reactive<FormRules>({
  pName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
});
interface OrderItem {
  productId: string;
  pNumber: number;
  pPrice: number;
}

let orderItems = ref<any>([]);
const tabledataChoose = (val: any) => {
  orderItems.value = [];
  val.map((item: any) => {
    orderItems.value.push({
      productId: item.id,
      pNumber: item.buyNumber,
      pPrice: item.pPrice,
    });
  });
};
const props = defineProps({
  visible: { type: Boolean, default: false },
  title: { type: String, default: "新增" },
  selectedRows: { type: Array, default: [] },
});
const selectedRowsUse: any = ref();
watch(
  () => props.selectedRows,
  (newValue) => {
    selectedRowsUse.value = newValue;
  }
);
let dialogVisible = ref(props.visible);
const emit = defineEmits(["update:visible", "saveSubmit"]);
watch(
  () => props.visible,
  (newValue) => {
    dialogVisible.value = newValue;
  }
);
watch(
  () => dialogVisible.value,
  (newValue) => {
    emit("update:visible", newValue);
  }
);
watch(
  () => dialogVisible.value,
  (newValue) => {
    emit("update:visible", newValue);
  }
);
// 获取商品分类列表
const getCategoryList = async () => {
  const res = await productApi.getCategoryList();
  const mappedList = res.data.list.map((item: any) => ({
    value: item.id,
    label: item.name,
  }));
  categoryList.value = res.data.list;
  return mappedList;
};
onMounted(async () => {
  const mappedList = await getCategoryList();
  formConfig.value = getFormConfig(mappedList);
});
const fileList = ref<UploadUserFile[]>([]);

const close = () => {
  // spursFormRef.value.ruleFormRef.clearValidate();
  fileList.value = [];
  dialogVisible.value = false;
};
const checkDescriptionsStrict = (
  data: Array<{ pNumber?: string | null }>
): boolean => {
  return data.every(
    (item) =>
      item.pNumber !== undefined && item.pNumber !== null && item.pNumber !== ""
  );
};

interface CreateOrderDto {
  customerId: string;
  addressId?: string | null; // 可选字段
  orderItems: OrderItem[]; // 这里明确是 OrderItem 的数组
  remark?: string | null;
  productRequirementId: string;
}
const saveSubmit = async () => {
  if (orderItems.value.length == 0) {
    ElMessage.error("请选择商品");
    return;
  }
  const every = checkDescriptionsStrict(orderItems.value);
  if (!every) {
    ElMessage.error("请输入下单商品数量");
    return;
  }

  const orderForm = reactive<CreateOrderDto>({
    customerId: selectedRowsUse.value[0].customer.id,
    addressId: "",
    orderItems: orderItems.value,
    remark: "",
    productRequirementId: selectedRowsUse.value[0].id,
  });
  const res = await orderApi.addOrder(orderForm);
  if (res.data.ok) {
    ElMessage.success("下单成功,请前往订单列表查看");
  } else {
    ElMessage.error("下单失败");
  }
  emit("saveSubmit");
};
</script>

<style scoped></style>
